"""
Copyright 2012 Wieser Dietmar, Margit Mutschlechner.

This file is part of Multimedia Social Networking Platform.

Multimedia Social Networking Platform is free software: 
you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Multimedia Social Networking Platform is distributed
in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Multimedia Social Networking Platform.  
If not, see <http://www.gnu.org/licenses/>.

"""

from threading import Thread
from msnp.logger import Logger
import traceback

class ListeningThread(Thread):
    """Thread for a daemon.

    This class contains a list of threads and several methods for stopping and starting the underlying daemons.

    Attributes:
        __daemon: The underlying daemon.
        __running: A boolean indicating the running status of the daemon.
        threads: A list containing all threads (class attribute).
    """
    
    threads = []
    
    def __init__(self, daemon):
        """the init method"""
        Thread.__init__(self)
        self.__daemon = daemon
        self.__running = True
        
    def run(self):
        """Starts the daemon based on the __running attribute."""
        try:
            self.__daemon.requestLoop(condition=lambda: self.__running)
            self.__daemon.shutdown()
        except:
            Logger.info(traceback.format_exc())
        
    def stop(self):
        """Stops the thread by setting __running to false."""
        
        self.__running = False
#        self.__daemon.shutdown()
    
    def getDaemon(self):
        """Returns the daemon attribute."""
        return self.__daemon
        
    @classmethod
    def addThread(cls, thread):
        """Adds a new ListeningThread instance to the threads list.
        
        Args:
            thread: a ListeningThread instance.
        """
        cls.threads.append(thread)
        
    @classmethod
    def startListening(cls):
        """Starts all ListeningThread instances in the thread list."""
        Logger.info("start listening")
        for thread in cls.threads:
            try:
                thread.start()
            except:
                Logger.info(traceback.format_exc())

    @classmethod
    def stopListening(cls):
        """Stops all ListeningThread instances in the thread list."""
        Logger.info("stop listening")
        for thread in cls.threads:
            thread.stop()
        cls.threads = []

